<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    :close-on-click-modal="false"
    width="750px"
    @close="close"
  >
    <!--  html  -->
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-suffix="：" label-width="120px" size="small">
      <el-form-item label="券名称">
        {{ form.couponName }}
      </el-form-item>
      <div v-if="['cash','discount','exchange'].includes(form.couponType)">
        <!-- 发放预算 -->
        <el-form-item label="发放预算">
          <el-form-item prop="maxCoupons">
            <el-checkbox v-model="form.maxCouponsChecked">设置有效期内可发放总上限为&nbsp;</el-checkbox>
            <el-input
              v-model="form.maxCoupons"
              :disabled="!form.maxCouponsChecked"
              placeholder="请输入"
              maxlength="10"
              class="w-200"
            >
              <template slot="append">次</template>
            </el-input>
          </el-form-item>
          <el-form-item prop="maxCouponsByDay">
            <el-checkbox v-model="form.maxCouponsByDayChecked">设置一个自然日可发放上限为&nbsp;</el-checkbox>
            <el-input
              v-model="form.maxCouponsByDay"
              :disabled="!form.maxCouponsByDayChecked"
              placeholder="请输入"
              maxlength="10"
              class="w-200"
            >
              <template slot="append">次</template>
            </el-input>
          </el-form-item>
        </el-form-item>
      </div>
      <div v-if="['cash_wx_busi','discount_wx_busi','cash_wx_pay'].includes(form.couponType)">
        <!-- 预算 -->
        <el-form-item label="发放预算" class="is-required">
          <el-form-item prop="maxCoupons">
            <span>批次总预算次数：&#12288;</span>
            <el-input v-model="form.maxCoupons" placeholder="请输入" maxlength="10" class="w-200">
              <template slot="append">次</template>
            </el-input>
            <span>&nbsp;1 ≤ 次数 ≤ 1000000000</span>
          </el-form-item>
          <el-form-item prop="maxCouponsByDay">
            <span>单天发放上限次数：</span>
            <el-input v-model="form.maxCouponsByDay" placeholder="请输入" maxlength="10" class="w-200">
              <template slot="append">次</template>
            </el-input>
            <span>&nbsp;1 ≤ 次数 ≤ 1000000000</span>
          </el-form-item>
        </el-form-item>
      </div>

      <div>
        <el-form-item label="发放商户" prop="sendMerchant" class="is-required">
          <el-select v-model="form.sendMerchant" placeholder="请选择" class="w-300">
            <el-option :value="1" label="本商户" />
            <el-option :value="2" label="本商户和已合作的所有商户" />
            <el-option :value="3" label="本商户和指定已合作的部分商户" />
          </el-select>
          <el-button
            v-if="form.sendMerchant===3"
            @click="openDialogMerchantsTree('sendMerchant')"
          >
            <span v-if="form.sendMerchantList.length">已选择&nbsp;<span
              class="app-text-color-danger"
            >{{ form.sendMerchantList.length }}</span>&nbsp;家商户</span>
            <span v-else>选择</span>
          </el-button>
        </el-form-item>
      </div>

      <div v-if="['cash','discount','exchange','cash_wx_busi','discount_wx_busi'].includes(form.couponType)">
        <!-- 核销商户 -->
        <el-form-item label="核销商户" class="is-required">
          <el-select v-model="form.verifyMerchant" placeholder="请选择" class="w-300">
            <el-option :value="1" label="本商户下所有店铺" />
            <el-option :value="2" label="本商户和已合作商户的所有店铺" />
            <el-option :value="3" label="指定本商户和已合作商户的部分店铺" />
          </el-select>
          <el-button
            v-if="form.verifyMerchant===3||form.verifyMerchant===4"
            @click="openDialogMerchantsTree('verifyMerchant')"
          >
            <span v-if="form.verifyMerchantList.length">已选择&nbsp;<span
              class="app-text-color-danger"
            >{{ form.verifyMerchantList.length }}</span>&nbsp;家商户</span>
            <span v-else>选择</span>
          </el-button>
        </el-form-item>
      </div>

      <div v-if="['cash_wx_pay'].includes(form.couponType)">
        <!-- 可核销商户号 -->
        <div>
          <el-form-item label="核销商户" prop="verifyMerchants">
            <el-card :body-style="{ 'padding-bottom': '0px' }" class="nest-card-box">
              <el-input v-model="form.verifyMerchants" :autosize="{ minRows: 3, maxRows: 10}" type="textarea" />
              <div>一行对应一个商户号(可通过Enter换行)，最多添加50个商户号，包含你自己的商户号</div>
            </el-card>
          </el-form-item>
        </div>
      </div>

      <div v-if="['cash','discount','exchange','cash_wx_busi','discount_wx_busi'].includes(form.couponType)">
        <!-- 核销业务 -->
        <el-form-item item label="核销业务" class="is-required">
          <el-select v-model="form.verifyBusinessType" placeholder="请选择" class="w-300">
            <el-option :value="1" label="所有的业务场景下可核销" />
            <el-option :value="2" label="指定部分业务场景下可核销" />
          </el-select>

          <div v-if="form.verifyBusinessType===2" class="nest-card-box" style="margin-top:10px">
            <el-card :body-style="{padding:'20px 20px 0 20px'}">
              <el-form-item prop="verifyBusiness">
                <el-checkbox-group v-model="form.verifyBusiness">
                  <template v-for="item in manageBizCodeOptions">
                    <el-checkbox v-if="item.usePay&&item.canDiscount" :key="item.value" :label="String(item.key)">
                      {{ item.label }}
                    </el-checkbox>
                  </template>
                </el-checkbox-group>
              </el-form-item>
            </el-card>
          </div>
        </el-form-item>
      </div>
    </el-form>

    <DialogMerchantsTree ref="dialogMerchantsTree" />

    <div slot="footer" class="dialog-footer">
      <el-button size="small" round @click="hide">取 消</el-button>
      <el-button size="small" round type="primary" @click="handleSubmit('form')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DialogMerchantsTree from '../../components/DialogMerchantsTree'
import CouponValidate from '../../editCoupon/mixin/CouponValidate'
import { authMerchants } from '../../../api/mch'
import { mapGetters } from 'vuex'
export default {
  components: {
    DialogMerchantsTree
  },
  mixins: [CouponValidate],
  data() {
    return {
      // 配置
      couponTypeOptions: {
        cash: '代金券',
        cash_wx_pay: '微信支付代金券',
        cash_wx_busi: '微信商家代金券',
        discount: '折扣券',
        discount_wx_busi: '微信商家折扣券',
        exchange: '兑换券'
      },
      couponTypeGroup: {
        cash: ['cash', 'cash_wx_pay', 'cash_wx_busi'],
        discount: ['discount', 'discount_wx_busi'],
        exchange: ['exchange']
      },
      title: '更新优惠券',
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      form: {
        belongMerchant: null, // 归属商户号
        maxCouponsChecked: true, // 是否勾选  no params
        maxCoupons: null, // 总预算 次数
        maxCouponsByDayChecked: true, // 是否勾选  no params
        maxCouponsByDay: null, // 日总预算 数量
        sendMerchant: 1, // 发券商户类型 1本商户
        sendMerchantList: [],
        verifyMerchant: 1, // 核销商户类型 1本商户  2本商户和所有合作商户 3本商户与合作商户指定门店  4本商户指定店铺
        verifyMerchantList: [],
        verifyMerchants: null, // 微信支付核销商户 需按行转,分割string
        verifyBusinessType: 1, // 业务类型 no params  1：所有 2：部分
        verifyBusiness: [] // 业务类型  需转,分割string
      }
    }
  },
  computed: {
    ...mapGetters([
      'manageBizCodeOptions'
    ])
  },
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {

  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    // 弹框相关
    open({ form }) {
      this.loading = true
      const params = JSON.parse(JSON.stringify((form)))
      Promise.all([this.getDetail(params), this.getAuthMerchants(params)]).finally(() => {
        this.show()
        this.loading = false
      })
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.loading = false
    },

    /**
     * 数据组
     */
    // 获取详情
    getDetail(params) {
      return new Promise((resolve) => {
        // 发放商户
        switch (params.sendMerchant) {
          case 1:
          case 2:
            params.sendMerchantList = []
            break
          case 3:
            params.sendMerchantList.forEach(v => {
              v.merchant = 'M-' + v.merchant
              v.shop = v.shop ? v.shop.split(',') : []
            })
            break
        }

        if (
          [
            'cash',
            'discount',
            'exchange',
            'cash_wx_busi',
            'discount_wx_busi'
          ].includes(params.couponType)
        ) {
          // 核销商户
          switch (params.verifyMerchant) {
            case 1:
            case 2:
              params.verifyMerchantList = []
              break
            case 3:
              params.verifyMerchantList.forEach(v => {
                v.merchant = 'M-' + v.merchant
                v.shop = v.shop ? v.shop.split(',') : []
              })
              break
          }
          // 核销业务
          if (params.verifyBusiness) {
            params.verifyBusiness = params.verifyBusiness.split(',')
            params.verifyBusinessType = 2
          } else {
            params.verifyBusinessType = 1
            params.verifyBusiness = []
          }
        } else {
          params.verifyBusinessType = 1
          params.verifyBusiness = []
        }
        // 格式化微信代金券 专用
        if (['cash_wx_pay'].includes(params.couponType)) {
          // 核券商户号
          params.verifyMerchants = params.verifyMerchants.replace(
            /,/g,
            '/n'
          )
          if (params.wxPayType) {
            params.wxPayTypeType = 1
            params.wxPayType = params.wxPayType.split(',')
          } else {
            params.wxPayTypeType = 2
            params.wxPayType = []
          }
        } else {
          params.wxPayTypeType = 1
          params.wxPayType = []
        }

        // 格式化预算
        params.maxCouponsChecked = true
        params.maxCouponsByDayChecked = true
        if (['cash', 'discount', 'exchange'].includes(params.couponType)) {
          params.maxCouponsChecked = !!params.maxCoupons
          params.maxCouponsByDayChecked = !!params.maxCouponsByDay
        }
        console.log('格式化完成', params)
        this.form = params
        resolve()
      })
    },

    // 获取合作商户
    getAuthMerchants(params) {
      return new Promise((resolve) => {
        if (params.belongMerchant) {
          authMerchants({ belongMerchant: params.belongMerchant }).then(res => {
            const allMchList = []
            res.data.forEach(v => {
              v.id = 'M-' + v.id
              allMchList.push(
                {
                  id: v.id,
                  name: v.name,
                  shops: []
                }
              )
            })
            this.allMchList = allMchList
            this.allMchShopList = res.data
          }).finally(() => {
            resolve()
          })
        } else {
          resolve()
        }
      })
    },

    // 打开商户
    openDialogMerchantsTree(mode) {
      let checkedIds = []
      let treeData = []
      if (mode === 'sendMerchant') {
        treeData = this.allMchList
        this.form.sendMerchantList.forEach(v => {
          checkedIds.push(v.merchant)
        })
      } else if (mode === 'verifyMerchant') {
        treeData = this.allMchShopList
        this.form.verifyMerchantList.forEach(v => {
          checkedIds = checkedIds.concat(v.shop)
        })
      }
      this.$refs.dialogMerchantsTree.open({ treeData, checkedIds }).then(res => {
        console.log('选择商户', res)
        if (mode === 'sendMerchant') {
          this.form.sendMerchantList = res
        } else if (mode === 'verifyMerchant') {
          this.form.verifyMerchantList = res
        }
      })
    },

    handleSubmit() {
      console.log(this.form)
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form))
          // 发放商户
          switch (params.sendMerchant) {
            case 1:
            case 2:
              params.sendMerchantList = []
              break
            case 3:
              params.sendMerchantList.forEach(v => {
                v.merchant = String(v.merchant).replace('M-', '')
                v.shop = v.shop.join()
              })
              break
          }

          if (
            [
              'cash',
              'discount',
              'exchange',
              'cash_wx_busi',
              'discount_wx_busi'
            ].includes(params.couponType)
          ) {
            // 核销商户
            switch (params.verifyMerchant) {
              case 1:
              case 2:
                params.verifyMerchantList = []
                break
              case 3:
                params.verifyMerchantList.forEach(v => {
                  v.merchant = String(v.merchant).replace('M-', '')
                  v.shop = v.shop.join()
                })
                break
            }
            // 核销业务
            params.verifyBusiness =
              params.verifyBusinessType === 1
                ? ''
                : params.verifyBusiness.join()
          }

          // 格式化微信代金券 专用
          if (['cash_wx_pay'].includes(params.couponType)) {
            // 核券商户号
            params.verifyMerchants = params.verifyMerchants
              .trim()
              .replace(/\s/g, '')
              .replace(/\n/g, ',')
              .replace(/,+/g, ',')
          }
          console.log(params)
        }
      })
    }
    /**
     * 按钮组
     */
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

.w-200 {
  width: 200px;
}
.w-300 {
  width: 300px;
}

.w-400 {
  width: 400px;
}
</style>
